package com.zkingsoft.thread;

import java.util.ArrayList;
import java.util.List;

import com.dingtalk.open.client.api.model.corp.MessageBody;
import com.dingtalk.open.client.api.model.corp.MessageBody.OABody.Body;
import com.dingtalk.open.client.api.model.corp.MessageBody.OABody.Body.Form;
import com.dingtalk.open.client.api.model.corp.MessageBody.OABody.Head;
import com.dingtalk.open.client.api.model.corp.MessageType;
import com.zkingsoft.dao.TaskDao;
import com.zkingsoft.dingding.Env;
import com.zkingsoft.dingding.Vars;
import com.zkingsoft.dingding.auth.AuthHelper;
import com.zkingsoft.dingding.message.LightAppMessageDelivery;
import com.zkingsoft.dingding.message.MessageHelper;
import com.zkingsoft.model.Task;

/**
 * 发送与客户问题反馈的消息通知线程类
 * 
 * @author Administrator
 *
 */
public class SendNoFinishTaskOaMsgsThread implements Runnable {

	TaskDao taskDao = null;
	String bgColor = null;
	String title = null;
	
	public SendNoFinishTaskOaMsgsThread(TaskDao taskDao, String bgColor, String title) {
		super();
		this.taskDao = taskDao;
		this.bgColor = bgColor;
		this.title = title;
	}

	@Override
	public void run() {
		sendNoFinishTaskOaMsgs();
	}

	public void sendNoFinishTaskOaMsgs() {
		try {
			// 循环发送OA消息
			List<Task> taskList = taskDao.selectNumNoFinish();
			if(taskList.size()>0 && taskList != null){
				String accessToken = AuthHelper.getAccessToken();// 获取accessToken
				String toParties = Vars.TO_PARTY;
				String agentId = Vars.AGENT_ID;
				String toUsers = "";
				for (Task task : taskList) {
					String ddUserId = task.getUserValidateCode();
					if(ddUserId!=null && !"".equals(ddUserId)){
						toUsers = ddUserId;
						// 创建oa消息
						MessageBody.OABody oaBody = createOaMsg(task);
						// 发送微应用消息
						LightAppMessageDelivery lightAppMessageDelivery = new LightAppMessageDelivery(toUsers, toParties, agentId);
						lightAppMessageDelivery.withMessage(MessageType.OA, oaBody);
						MessageHelper.send(accessToken, lightAppMessageDelivery);						
					}
				}
			}		
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * @Description:创建OA消息
	 * @author:dingchuan
	 * @param task
	 * @return 返回类型 MessageBody.OABody
	 * @date 2016年12月6日
	 */
	public MessageBody.OABody createOaMsg(Task task) {
		MessageBody.OABody oaBody = new MessageBody.OABody();
		oaBody.setMessage_url(Env.LOOK_NO_FINDISH_TASKS + task.getUserId());
		oaBody.setPc_message_url(Env.LOOK_NO_FINDISH_TASKS + task.getUserId());
		// 头部
		Head head = new Head();
		head.setText("");
		head.setBgcolor(bgColor);
		oaBody.setHead(head);
		// 内容
		Body body = new Body();
		body.setTitle("你还有"+task.getNoFinishTaskNum()+"个任务未完成哦，请尽快完成");//反馈的标题
		List<Form> formList = new ArrayList<Form>();
		Form form1 = new Form();
		form1.setKey("类型");
		form1.setValue(this.title);
		formList.add(form1);
		body.setForm(formList);
		oaBody.setBody(body);
		return oaBody;
	}

}
